<template>
  <div class="publish">
    <h1>发布笔记</h1>
    <el-form :model="form" label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="form.title" maxlength="50" />
      </el-form-item>
      <el-form-item label="内容">
        <el-input v-model="form.content" type="textarea" rows="5" />
      </el-form-item>
      <el-form-item label="图片">
        <el-upload
          action=""
          :http-request="uploadImage"
          accept="image/jpeg,image/png"
          :limit="1"
        >
          <el-button>上传图片</el-button>
        </el-upload>
      </el-form-item>
      <el-button type="primary" @click="submit">发布</el-button>
    </el-form>
  </div>
</template>

<script setup>
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { useAuthStore } from '../stores/auth';

const router = useRouter();
const authStore = useAuthStore();
const form = reactive({ title: '', content: '', image: null });

if (!authStore.token) {
  router.push('/login?redirect=/publish');
}

const uploadImage = async ({ file }) => {
  form.image = file;
};

const submit = async () => {
  try {
    const formData = new FormData();
    formData.append('title', form.title);
    formData.append('content', form.content);
    if (form.image) formData.append('image', form.image);

    await axios.post('/api/notes', formData, {
      headers: { Authorization: `Bearer ${authStore.token}` },
    });
    router.push('/explore');
  } catch (error) {
    alert('发布失败：' + (error.response?.data?.message || '未知错误'));
  }
};
</script>

<style scoped>
.publish { max-width: 800px; margin: 20px auto; padding: 20px; }
</style>